import { MessageBox } from '../../components/MessageBox'
import { makeAutoObservable, runInAction } from 'mobx'
import { CommonApi } from '../../api/index'
import { setCookie, removeCookie } from '@fallen_leaves/fe-utils'

function deepMapPermissions (
  source: UserStoreTypes.MenuItemProps[],
  target: Record<string, UserStoreTypes.PermissionItemProps> = {},
  parent?: UserStoreTypes.MenuItemProps
) {
  source.forEach(menu => {
    if (menu.url) {
      target[menu.url] = {
        operations: menu.operations || [],
        label: menu.label,
        url: menu.url,
        parent
      }
    }
    if (menu.children) {
      deepMapPermissions(menu.children, target, menu)
    }
  })

  return target
}

export default class UserStore implements UserStoreTypes.UserStore {

  userInfo: UserStoreTypes.UserInfoProps = {
    userId: '',
    userAccount: '',
    userName: ''
  }

  menuList: UserStoreTypes.MenuItemProps[] = []

  permissions: Record<string, UserStoreTypes.PermissionItemProps> = {}

  rootStore: any

  constructor (rootStore: any) {
    makeAutoObservable(this, { rootStore: false })
    this.rootStore = rootStore
  }
  /**
   * @name 登录
   * @param loginInfo 登录信息
   * @param remember 是否记住登录状态
   */
  async login (loginInfo: { userAccount: string, password: string }, remember = false) {
    const userInfo = await CommonApi.login(loginInfo, { isFree: true }) as unknown as UserStoreTypes.UserInfoProps
    runInAction(() => {
      this.userInfo = userInfo
    })
    setCookie('ADMIN_USER_ID', userInfo.userId, {
      expirse: remember ? 30 : 0
    })
    setCookie('ADMIN_AUTN_TOKEN', userInfo.token, {
      expirse: remember ? 30 : 0
    })
  }
  /**
   * @name 登出
   * @param isAuto 是否过期自动退出
   */
  async logout () {
    await MessageBox.confirm({
      content: '确认清空当前登录信息，返回登录界面？',
      okText: '确认',
      cancelText: '取消'
    })
    runInAction(() => {
      this.userInfo = {
        userAccount: '',
        userId: '',
        userName: ''
      }
    })
    removeCookie('ADMIN_USER_ID')
    removeCookie('ADMIN_AUTN_TOKEN')
    this.rootStore.layoutStore.clearTabs()
  }
  /**
   * @name 获取用户信息
   */
  async getUserInfo () {
    const userInfo = await CommonApi.getUserInfo({ userId: this.userInfo.userId }) as unknown as UserStoreTypes.UserInfoProps
    runInAction(() => {
      this.userInfo = userInfo
    })
  }
  /**
   * @name 获取用户菜单列表
   */
  async getUserMenu () {
    const menuList = await CommonApi.getUserMenu({ userId: this.userInfo.userId }) as unknown as UserStoreTypes.MenuItemProps[]
    runInAction(() => {
      this.menuList = menuList
      this.permissions = deepMapPermissions(menuList)
    })
  }
}
